package com.utils;

import com.opencsv.bean.CsvToBeanBuilder;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : wilbur.yuan
 * @date : 2019-04-16
 */
public class Starter {

    private static String update_sql = "UPDATE XIMA_VIP_CLR.VIP_ORDER_PROFIT_01$!{tableIndex} SET DURATION_DAYS = (SELECT a.DURATION_DAYS FROM (SELECT DURATION_DAYS FROM VIP_ORDER_PROFIT_01$!{tableIndex} WHERE MERCHANT_ORDER_NO = '$!{newOrderNo}') a), START_TIME=(SELECT a.START_TIME FROM (SELECT START_TIME FROM VIP_ORDER_PROFIT_01$!{tableIndex} WHERE MERCHANT_ORDER_NO = '$!{newOrderNo}') a), END_TIME=(SELECT a.END_TIME FROM (SELECT END_TIME FROM VIP_ORDER_PROFIT_01$!{tableIndex} WHERE MERCHANT_ORDER_NO = '$!{newOrderNo}') a) WHERE MERCHANT_ORDER_NO = '$!{oldOrderNo}';";

    private static String del_sql = "DELETE FROM VIP_ORDER_PROFIT_01$!{tableIndex}  WHERE MERCHANT_ORDER_NO = '$!{newOrderNo}';";

    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();

        String csvFile = "/Users/xmly/GiteeProjects/utils/csv-reader/src/main/java/com/utils/result1.csv";

        InputStream inputStream = getInputStream(new FileInputStream(csvFile));

        InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));

        List<OrderProfit> orderProfits = new CsvToBeanBuilder(reader).withType(OrderProfit.class).build().parse();

        Map<Long, List<OrderProfit>> map = orderProfits.stream().collect(Collectors.groupingBy(OrderProfit::getUid));

        for (List<OrderProfit> orderProfits1 : map.values()) {


            orderProfits1.sort((OrderProfit o1, OrderProfit o2) -> o1.getPurchaseTime().before(o2.getPurchaseTime()) ? -1 : 1);

            List<OrderProfit> oldList = orderProfits1.stream().filter(o -> o.getAmount().doubleValue() > 0).collect(Collectors.toList());
            if (orderProfits1.size() > 4 && oldList.size() > 0)

                System.out.println(orderProfits1.get(0).getUid());

            oldList.stream().forEach(orderProfit ->
                    orderProfits1.stream()
                            .filter(o -> o.getAmount().doubleValue() == 0)
                            .filter(o -> o.getItemId().equals(orderProfit.getItemId()))
                            .skip(oldList.indexOf(orderProfit))
                            .findFirst()
                            .ifPresent(o -> getSqlForPair(sb, Arrays.asList(orderProfit, o)))
            );

        }

        System.out.println(sb.toString());
    }

    private static void getSqlForPair(StringBuilder sb, List<OrderProfit> orderProfits1) {
        OrderProfit o = orderProfits1.get(0);
        OrderProfit n = orderProfits1.get(1);

        if (BigDecimal.ZERO.compareTo(o.getAmount()) == 0)
            return;
        Map<String, Object> params = new HashMap<>();

        long tableIndex = o.getUid() % 100;
        params.put("tableIndex", StringUtils.leftPad(tableIndex + "", 2, '0'));
        params.put("newOrderNo", n.getOrderNo());
        params.put("oldOrderNo", o.getOrderNo());

        String usql = VelocityParserUtil.getInstance().parseVelocityTemplate(update_sql, params, "updateTemplate");
        sb.append(usql).append("\n");
//        String dsql = VelocityParserUtil.getInstance().parseVelocityTemplate(del_sql, params, "updateTemplate");
//        sb.append(dsql).append("\n");
    }


    public static InputStream getInputStream(InputStream in) throws IOException {

        PushbackInputStream testin = new PushbackInputStream(in);
        int ch = testin.read();
        if (ch != 0xEF) {
            testin.unread(ch);
        } else if ((ch = testin.read()) != 0xBB) {
            testin.unread(ch);
            testin.unread(0xef);
        } else if ((ch = testin.read()) != 0xBF) {
            throw new IOException("错误的UTF-8格式文件");
        } else {
        }
        return testin;
    }
}
